﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SystemUpdatesCore;
using SystemUpdatesCore.Server;
using SystemUpdatesCore.Server.Network;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();


            this.Loaded += MainWindow_Loaded;
        }
        INetworkClient networkClient = new NetworkHttpClient();

        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {

            var ver = $"https://gitee.com/ypeuee/MouseKeyMacro.Simple.Publish/raw/master/version ";

            var str =await networkClient.DownloadStringTaskAsync(ver);

            ServerVersionModel version = str.ToObject<ServerVersionModel>();

            /* 
             * 下载进度：100
             * 文件解压：10
             * 总进度：总进度进度+单文件解压 =110
             * 
             * 
             */

            int totalBar = 0;
            long totalFileSize = 0;
            long downTotalSize = 0;
            long oneFileBar = 0;
            int oneZipBar = 0;
            foreach (var file in version.UpdateFiles)
            {
                long size = file.FileSize;
                    totalFileSize += size;
            }
            oneFileBar = totalFileSize / 100;
            oneZipBar = version.UpdateFiles.Count() / 10;

            bar1.Maximum = 110;

            foreach (var file in version.UpdateFiles)
            {
                await networkClient.DownloadFileTaskAsync(version.DownUrls[0] + file.DownUrl, file.FileName);

                networkClient.DownloadProgressChanged += (s, e) =>
                {
                    downTotalSize += e.TotalBytesToReceive;
                    
                    if(downTotalSize / oneFileBar> totalBar)
                    {
                        totalBar++;

                        UpdBarValue(totalBar);
                    }
                };
                networkClient.DownloadFileCompleted += (s, e) =>
                {

                };

                //task.Wait();
                //Task.WaitAll(task);
            }
             
            //UpdBarValue( 110);
        }

        void UpdBarValue(int value)
        {
            if (bar1.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
                bar1.Dispatcher.Invoke(() => bar1.Value = value);
            else
                bar1.Value = value;
        }
    }
}
